package com.java.controller;

import cn.hutool.core.util.EnumUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.java.common.constant.CookieConstant;
import com.java.common.enums.OrderStatusEnum;
import com.java.common.enums.PayMethod;
import com.java.common.utils.CookieUtils;
import com.java.common.utils.IMOOCJSONResult;
import com.java.common.utils.PageUtils;
import com.java.common.utils.R;
import com.java.pojo.OrderStatus;
import com.java.pojo.Orders;
import com.java.pojo.bo.SubmitOrderBO;
import com.java.pojo.vo.MerchantOrdersVO;
import com.java.service.OrderStatusService;
import com.java.service.OrdersService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 订单表;
 *
 * @author jl
 * @since 2020-10-13 11:31:41
 */
@RestController
@RequestMapping("/orders")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private OrderStatusService orderStatusService;

    // 支付中心的调用地址
    public static final String PAYMENT_URL = "http://payment.t.mukewang.com/foodie-payment/payment/createMerchantOrder";		// produce

    // 回调地址
    public static final String PAY_RETURN_URL = "http://qkpfb4.natappfree.cc/orders/notifyMerchantOrderPaid";

    @ApiOperation("用户下单")
    @PostMapping("/create")
    public R create(@RequestBody SubmitOrderBO submitOrderBO, HttpServletRequest request, HttpServletResponse response) {
        List<Object> types = EnumUtil.getFieldValues(PayMethod.class, "type");
        if (!types.contains(submitOrderBO.getPayMethod())) {
            return R.error("不支持的支付方式");
        }
        MerchantOrdersVO merchantOrdersVO = ordersService.createOrder(submitOrderBO);

        // todo 购物车移除已购物的商品
        CookieUtils.setCookie(request, response, CookieConstant.FOODIE_SHOPCART, "", true);

        // 3. 向支付中心发送当前订单，用于保存支付中心的订单数据
        merchantOrdersVO.setReturnUrl(PAY_RETURN_URL);

        // 为了方便测试购买，所以所有的支付金额都统一改为1分钱
        merchantOrdersVO.setAmount(1);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.add("imoocUserId","imooc");
        headers.add("password","imooc");
        merchantOrdersVO.setAmount(1);
        HttpEntity<MerchantOrdersVO> entity = new HttpEntity<>(merchantOrdersVO, headers);

        ResponseEntity<IMOOCJSONResult> responseEntity =
                restTemplate.postForEntity(PAYMENT_URL, entity, IMOOCJSONResult.class);
        IMOOCJSONResult paymentResult = responseEntity.getBody();
        assert paymentResult != null;
        if (paymentResult.getStatus() != 200) {
            log.error("发送错误：{}", paymentResult.getMsg());
            return R.error("支付中心订单创建失败，请联系管理员！");
        }

        return R.ok(merchantOrdersVO.getMerchantOrderId());
    }

    @PostMapping("/notifyMerchantOrderPaid")
    public int notifyMerchantOrderPaid(@RequestParam String merchantOrderId){
        ordersService.updateOrderStatus(merchantOrderId, OrderStatusEnum.WAIT_DELIVER.type);
        return HttpStatus.OK.value();
    }

    @PostMapping("/getPaidOrderInfo")
    public R getPaidOrderInfo(@RequestParam String orderId) {
        OrderStatus orderStatus = orderStatusService.getById(orderId);
        return R.ok(orderStatus);
    }

    /**
     * 带条件分页查询订单表;
     */
    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = ordersService.queryPage(params);

        return R.ok(page);
    }


    /**
     * 根据主键查询订单表;
     */
    @GetMapping("/info/{id}")
    public R info(@PathVariable("id") String id) {
        Orders orders = ordersService.getById(id);

        return R.ok(orders);
    }

    /**
     * 新增订单表;
     */
    @PostMapping("/save")
    public R save(@RequestBody Orders orders) {
        ordersService.save(orders);

        return R.ok();
    }

    /**
     * 修改订单表;
     */
    @PutMapping("/update")
    public R update(@RequestBody Orders orders) {
        ordersService.updateById(orders);

        return R.ok();
    }

    /**
     * 删除订单表;
     */
    @DeleteMapping("/delete")
    public R delete(@RequestBody String[] ids) {
        ordersService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

    // 查询支付中心,订单是否创建成功
    public static void main(String[] args) {
        String url = "http://payment.t.mukewang.com/foodie-payment/payment/getPaymentCenterOrderInfo";
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("merchantOrderId","1317750469094936576");
        paramMap.put("merchantUserId","1908017YR51G1XWH");
        //链式构建请求
        String result = HttpRequest.post(url)
                .header("imoocUserId", "imooc").header("password", "imooc")//头信息，多个头信息多次调用此方法即可
                .form(paramMap)
                .execute().body();
        JSONObject r = JSON.parseObject(result, JSONObject.class);
        System.out.println(r.get("data"));
    }

}
